﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：庄金冬 
    //
    // 文件名：BLL_Hospital.cs
    // 文件功能描述：医疗机构操作业务逻辑类,实现接口IBLL_Hospital,继承自类MarshalByRefObject
    // 创建标识：庄金冬2009-03-06
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
    // 审核时间：
    // 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Text;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.DAL;
using System.Data;
namespace HZ.DrugTrade.BLL
{

    [Serializable]
    /// <summary>
    /// 医疗机构操作业务逻辑类,实现接口IBLL_Hospital,继承自类MarshalByRefObject
    /// </summary>
    public class BLL_Hospital : MarshalByRefObject, IBLL_Hospital
    {


        #region IBLL_Hospital 成员

        /// <summary>
        /// 获取最新可用医疗机构编号
        /// </summary>
        /// <returns>最新可用医疗机构编号</returns>
        public string GetNewHospitalID()
        {
            return DAL_Hospital.GetNewHospitalID();
        }

        /// <summary>
        /// 获取所有医疗机构
        /// </summary>
        /// <returns>所有医疗机构</returns>
        public IList<Hospital> GetAllHospital()
        {
            return DAL_Hospital.GetAllHospital();
        }


        /// <summary>
        /// 编辑医疗机构
        /// </summary>
        /// <returns>True:成功;False:失败</returns>
        public bool UpdateHospital(Hospital hospital)
        {
            BLL_UserSession.CheckSession();
            bool state = DAL_Hospital.UpdateHospital(hospital);
            if(state == true)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("编辑医疗机构：{0};处理时间:{1};)", hospital.HospitalID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }

        /// <summary>
        /// 删除医疗机构
        /// </summary>
        /// <param name="hospital">医疗机构</param>
        /// <returns>0.删除失败;1.删除成功;2.已被使用不能删除;</returns>
        public int DeleteHospital(Hospital hospital)
        {
            BLL_UserSession.CheckSession();
            int state = DAL_Hospital.DeleteHospital(hospital);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("删除医疗机构：{0};处理时间:{1};)", hospital.HospitalID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }
        /// <summary>
        /// 物理删除医疗机构
        /// </summary>
        /// <param name="HospitalID">医疗机构ID</param>
        /// <param name="type">删除类型 1 采购信息 2 删除采购目录信息 3 删除医疗机构及权限</param>
        /// <returns>0 删除失败 1 删除成功 2有相关信息取消删除</returns>
        public  int Delete_physicsHospital(String HospitalID, string type)
        {
            BLL_UserSession.CheckSession();
            int state = DAL_Hospital.Delete_physicsHospital(HospitalID, type);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("删除医疗机构：{0};处理时间:{1};)", HospitalID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }

        /// <summary>
        /// 添加医疗机构
        /// </summary>
        /// <param name="hospital">医疗机构</param>
        /// <returns>0.添加失败;1.添加成功;2.已经存在;</returns>
        public int AddHospital(Hospital hospital)
        {
            BLL_UserSession.CheckSession();
            int state = DAL_Hospital.AddHospital(hospital);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("添加医疗机构：{0};处理时间:{1};)", hospital.HospitalID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;

        }

        /// <summary>
        /// 获取所有未注册医疗机构
        /// </summary>
        /// <returns>所有未注册医疗机构</returns>
        public IList<Hospital> GetAllUnregHospital()
        {
            BLL_UserSession.CheckSession();
            return DAL_Hospital.GetAllUnregHospital();
        }

        /// <summary>
        /// 条件查询医疗机构
        /// </summary>
        /// <param name="hospital">查询用实体</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns></returns>
        public IList<Hospital> GetHospitalByWhere(HZ.DrugTrade.Model.Query.Hospital hospital, int currentPage, int pageSize, out int totalRecord)
        {
            return DAL_Hospital.GetHospitalByWhere(hospital, currentPage, pageSize, out totalRecord);
        }
        /// <summary>
        /// 自助注册一个新医疗机构信息
        /// </summary>
        /// <param name="companyinfo"></param>
        /// <returns>1成功2重名0失败</returns>
        public int RegNewHospital(Model.HospitalInfo hospitalinfo)
        {
            try
            {
                int state =HZ.Data.DAL_Helper.OperateTableSQL(hospitalinfo, HZ.Data.TableOperator.Insert);
                if(state == 1)
                {
                    BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("自助注册一个新医疗机构信息：{0};处理时间:{1};)", hospitalinfo.HospitalID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
                }
                return state;
            }
            catch (System.Data.SqlClient.SqlException ee)
            {
                return 2;
            }
        }
        /// <summary>
        /// 自助注册一个新医疗机构信息
        /// </summary>
        /// <param name="companyinfo"></param>
        /// <returns>1成功2医疗机构名称存在3医疗机构编号存在0失败</returns>
        public int RegNewHospital(Model.Hospital hospital, Model.HospitalInfo hospitalinfo)
        {
            var h = HZ.Data.DbHelperFactory.Create();

            //判断是否重名
            HZ.DrugTrade.Model.Query.Hospital q = new HZ.DrugTrade.Model.Query.Hospital();
            q.Append = string.Format(" HospitalName='{0}' ", hospital.HospitalName.Trim());
            int totalRecord=0;
            GetHospitalByWhere(q, 0, 0, out totalRecord);

            if (totalRecord>0)
            {
                return 2;
            }

            //判断是否重名
            HZ.DrugTrade.Model.Query.HospitalInfo q2 = new HZ.DrugTrade.Model.Query.HospitalInfo();
            q2.Append = string.Format(" HospitalName='{0}' ", hospital.HospitalName.Trim());
            int totalRecord2 = 0;
            GetHospitalByWhere(q, 0, 0, out totalRecord2);

            if (totalRecord2 > 0)
            {
                return 2;
            }

            q = new HZ.DrugTrade.Model.Query.Hospital() { HospitalID = hospital.HospitalID.Trim() };

            totalRecord = 0;
            GetHospitalByWhere(q, 0, 0, out totalRecord);

            if (totalRecord > 0)
            {
                return 3;
            }

            string strSql = string.Empty;
            try
            {
                h.BeginTrans();

                strSql = string.Format(@"
 		INSERT INTO TB_Hospital(HospitalID ,AreaID ,HospitalName ,HospitalAddress ,ContactPerson ,ContactTel ,SNKEY ) 
 		VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", hospital.HospitalID, hospital.AreaID, hospital.HospitalName, hospital.HospitalAddress, hospital.ContactPerson, hospital.ContactTel, string.Empty);
                h.ExecuteNonQuery(strSql);
               
                //strSql = HZ.Data.DAL_Helper.GetInsertSql(hospitalinfo);                
                //h.ExecuteNonQuery(strSql);

                HZ.Data.DAL_Helper.OperateTableSQL<Model.HospitalInfo>(hospitalinfo,HZ.Data.TableOperator.Insert,h);



                //strSql = HZ.Data.DAL_Helper.GetInsertSql(hospitalinfo);
                
                //h.ExecuteNonQuery(strSql);               

                h.CommitTrans();
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("自助注册一个新医疗机构信息：{0};处理时间:{1};)", hospitalinfo.HospitalID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
                return 1;

            }
            catch (System.Data.SqlClient.SqlException ee)
            {
                h.RollTrans();
                HZ.Common.log4netManager.LogDebug("RegNewHospital(Model.Hospital ,Model.HospitalInfo )", ee.Message, ee);
                return 0;
            }
        }


        /// <summary>
        /// 将系统帐户与医疗机构信息进行关联
        /// </summary>
        /// <param name="companyinfo"></param>
        /// <param name="?"></param>
        /// <returns></returns>
        public int MarkLinkToHospitalInfo(Model.HospitalInfo hospitalinfo, Model.Hospital hospital)
        {
            int state =  DAL.DAL_Hospital.MarkLinkTHospitalInfo(hospitalinfo, hospital);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("将系统帐户与医疗机构信息进行关联：{0};处理时间:{1};)", hospitalinfo.HospitalID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }

        /// <summary>
        /// 获取注册医疗机构信息
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentpage"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalrecord"></param>
        /// <returns></returns>
        public IList<Model.HospitalInfo> GetRegedHospitalInfo(Model.Query.HospitalInfo where, int currentpage, int pagesize, out int totalrecord)
        {
            return DAL.DAL_Hospital.GetRegedHospitalInfo(where, currentpage, pagesize, out totalrecord);
        }

        /// <summary>
        /// 审核医疗机构
        /// </summary>
        /// <param name="hospitalinfo"></param>
        /// <returns></returns>
        public Hospital AuditHospital(Model.HospitalInfo hospitalinfo)
        {
            var sh = HZ.Data.DbHelperFactory.Create();
            Hospital hospital = new Hospital();
            try
            {
                sh.BeginTrans();
                // 获取最大hospitalID
                object o = sh.ExecuteScalar("SELECT MAX(HospitalID) FROM TB_Hospital");
                string id = string.Empty;

                if (o == null)
                {
                    id = "H0001";
                }
                else
                {
                    id = o.ToString();
                    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\d+");
                    int rn = int.Parse(regex.Match(id).Value);
                    rn++;
                    id = "H" + rn.ToString("D4");
                }

                hospital.HospitalAddress = hospitalinfo.Address;
                hospital.HospitalID = id;
                hospital.ContactPerson = hospitalinfo.ContactPerson;
                hospital.HospitalName = hospitalinfo.HospitalName;
                hospital.ContactTel = hospitalinfo.TelNo;

                hospital.AreaID = hospitalinfo.AreaID;


                IDataParameter[] paras = HZ.Data.DAL_Helper.GetDataParameter(hospital);
                sh.ExecuteNonQuery(CommandType.StoredProcedure, "usp_Hospital_Add", paras);
                sh.CommitTrans();
            }
            catch (Exception)
            {

                sh.RollTrans();
                throw;
            }
            return hospital;

        }

        /// <summary>
        /// 获取未注册授权的医疗机构列表
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentpage"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalrecord"></param>
        /// <returns></returns>
        public IList<Model.HospitalInfo> GetUnregedHopialInfo(Model.Query.HospitalInfo where, int currentpage, int pagesize, out int totalrecord)
        {
            IList<Model.HospitalInfo> list = DAL_Hospital.GetUnregedHopialInfo(where, currentpage, pagesize, out totalrecord);

            return list;
        }

        /// <summary>
        /// 批量审核医疗机构
        /// </summary>
        /// <param name="hospitallist"></param>
        /// <returns></returns>
        public int AuditHospital(IList<Model.HospitalInfo> hospitallist)
        {
            int state = DAL.DAL_Hospital.AuditHospital(hospitallist);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("批量审核医疗机构;处理时间:{0};)", DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;

        }

        /// <summary>
        /// 删除不需要的医疗机构列表
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int DeleteHospitalInfo(IList<Model.HospitalInfo> list)
        {
            int state = DAL_Hospital.DeleteHospitalInfo(list);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("删除不需要的医疗机构列表;处理时间:{0};)", DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }
        /// <summary>
        /// 更新医疗机构信息
        /// </summary>
        /// <param name="hospitalinfo">医疗机构名ID等不能空</param>
        /// <param name="hospital">>医疗机构名ID等不能空</param>
        /// <param name="updateHospitalName">>是否更新医疗机构名称</param>
        /// <returns>1成功2重名0失败</returns>
        public int UpdateHospitalInfo2(Model.HospitalInfo hospitalinfo, Model.Hospital hospital, bool updateHospitalName)
        {
            HZ.Common.ThrowHelper.Throw(hospital.AreaID == hospital.AreaID);
            HZ.Common.ThrowHelper.Throw(hospital.HospitalID == hospital.HospitalID);
            HZ.Common.ThrowHelper.Throw(hospital.HospitalName == hospital.HospitalName);



            HZ.Data.IDbHelper sh = HZ.Data.DbHelperFactory.Create();

            if (updateHospitalName)
            {
                //判断是否存在重名
                HZ.DrugTrade.Model.Query.Hospital q = new HZ.DrugTrade.Model.Query.Hospital();
                q.Append = string.Format(" HospitalName='{0}' AND HospitalID<>'{1}'", hospital.HospitalName.Trim(), hospital.HospitalID.Trim());
                int totalRecord = 0;
                GetHospitalByWhere(q, 0, 0, out totalRecord);

                if (totalRecord > 0)
                {
                    return 2;
                }
            }           

            try
            {
                sh.BeginTrans();

                //更新TB_Hospital
                string sql1 = "";
                //更新TB_HospitalInfo
                string sql2 = "";


                /*
                 * by sinodier 20100818
                 这里有个BUG：就是在生成更新TB_HospitalInfo脚本时，默认不会更新主键hospitalname，而且是以主键hospitalname作为条件进行更新
                 * 当需要更改hospitalname时则没有办法，甚至会产生所有字段都无法更改
                 * 
                 * 修复：可以更改hospitalname，且是根据HospitalID进行更改
                 */
                //更新医疗机构名称
                if (updateHospitalName)
                {
                    //根据HospitalID进行更改TB_User表的UserName
                    sh.ExecuteNonQuery(string.Format(" update TB_User set UserName='{0}' where  UserID='{1}' ", hospitalinfo.HospitalName, hospitalinfo.HospitalID));
                    //根据HospitalID进行更改TB_HospitalInfo表的hospitalname
                    sh.ExecuteNonQuery(string.Format(" update TB_HospitalInfo set HospitalName='{0}' where  HospitalID='{1}' ", hospitalinfo.HospitalName, hospitalinfo.HospitalID));
                    HZ.Data.DAL_Helper.UpdateModel<Hospital>(hospital);
                    HZ.Data.DAL_Helper.UpdateModel<HospitalInfo>(hospitalinfo);


                    //注释部分拼接bool值类型sql 会在字符串中出现true or false，而oracle为numer类型 不能接受‘true’or 'false'
                    //sql1 = HZ.Data.DAL_Helper.GetUpdateSql(hospital);               
                    //sql2 = System.Text.RegularExpressions.Regex.Replace(HZ.Data.DAL_Helper.GetUpdateSql(hospitalinfo).ToLower(), @"and hospitalname='(.*)'", string
                    //    .Format( @"and HospitalID='{0}'",hospitalinfo.HospitalID.Trim()));
                }
                else //不更新医疗机构名称
                {
                    HZ.Data.DAL_Helper.UpdateModel<Hospital>(hospital);

                    HZ.Data.DAL_Helper.UpdateModel<HospitalInfo>(hospitalinfo);

#region 改版
                    //注释部分拼接bool值类型sql 会在字符串中出现true or false，而oracle为numer类型 不能接受‘true’or 'false'
                    //sql1 = System.Text.RegularExpressions.Regex.Replace(HZ.Data.DAL_Helper.GetUpdateSql(hospital).ToLower(), @"hospitalname='(.*)',", " ");
                    //sql1 = HZ.Data.DAL_Helper.GetUpdateSql(hospital).ToLower();
                    //sql2 = System.Text.RegularExpressions.Regex.Replace(HZ.Data.DAL_Helper.GetUpdateSql(hospitalinfo).ToLower(), @"and hospitalname='(.*)'",                       string.Format(@"and HospitalID='{0}'", hospitalinfo.HospitalID.Trim()));
                   
                }

               // if (!string.IsNullOrEmpty(sql1))
               // {                    
               //     sh.ExecuteNonQuery(sql1);
               // }
               // sh.ExecuteNonQuery(sql2);

                //sh.ExecuteNonQuery(string.Format(" update TB_HospitalInfo set HospitalName='{0}' where  HospitalID='{1}' ", hospitalinfo.HospitalName, hospitalinfo.HospitalID));
#endregion
                //内蒙交易内不能更新医疗机构名称，医疗机构名称会超时。数据库设计问题。  
              //  string sql1 = System.Text.RegularExpressions.Regex.Replace(HZ.Data.DAL_Helper.GetUpdateSql(hospital), @"HospitalName='(.*)',", " ");                
                //string sql2 = System.Text.RegularExpressions.Regex.Replace(HZ.Data.DAL_Helper.GetUpdateSql(hospitalinfo), @"hospitalName='(.*)',", " ");             
             //   sh.ExecuteNonQuery(sql1 + ";" + sql2);


                //修正 去掉部分索引 by sinodier 20100816
               
                sh.CommitTrans();
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("更新医疗机构信息：{0};处理时间:{1};)", hospitalinfo.HospitalID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
                return 1;
            }
            catch (Exception ee)
            {
                sh.RollTrans();
                HZ.Common.log4netManager.LogDebug(" HZ.DrugTrade.BLL.BLL_Hospital  UpdateHospitalInfo2(Model.Hospital ,Model.HospitalInfo,updateHospitalName)", ee.Message, ee);
                return 0;
            }
        }



        /// <summary>
        /// 更新医疗机构信息
        /// </summary>
        /// <param name="hospitalinfo">医疗机构名ID等不能空</param>
        /// <param name="hospital">>医疗机构名ID等不能空</param>
        /// <returns></returns>
        public int UpdateHospitalInfo(Model.HospitalInfo hospitalinfo, Model.Hospital hospital)
        {
            HZ.Common.ThrowHelper.Throw(hospital.AreaID == hospital.AreaID);
            HZ.Common.ThrowHelper.Throw(hospital.HospitalID == hospital.HospitalID);
            HZ.Common.ThrowHelper.Throw(hospital.HospitalName == hospital.HospitalName);

          //  string sql1 = HZ.Data.DAL_Helper.GetUpdateSql(hospital);
          //  string sql2 = HZ.Data.DAL_Helper.GetUpdateSql(hospitalinfo);
          //不更新医疗机构TB_Hospital 表 TB_Hospital表信息由数据库执行计划更新
          //  return HZ.Data.DbHelperFactory.Create().ExecuteNonQuery(sql1 + ";" + sql2) > 0 ? 1 : 0;
            int state = HZ.Data.DAL_Helper.OperateTableSQL(hospitalinfo, HZ.Data.TableOperator.Update, HZ.Data.DbHelperFactory.Create()) > 0 && HZ.Data.DAL_Helper.OperateTableSQL(hospital, HZ.Data.TableOperator.Update, HZ.Data.DbHelperFactory.Create())>0 ? 1 : 0;
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("更新医疗机构信息：{0};处理时间:{1};)", hospitalinfo.HospitalID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }
        /// <summary>
        /// 根据医疗机构ID获取医疗机构其它信息
        /// </summary>
        /// <param name="hospitalid"></param>
        /// <returns></returns>
        public HospitalInfo GetHospitalInfoByID(string hospitalid)
        {
            return DAL.DAL_Hospital.GetHospitalInfoByID(hospitalid);
        }

        /// <summary>
        /// 获取所有医疗机构等级详细
        /// </summary>
        /// <returns></returns>
        public List<string> GetHospitalinfoLevelDetail()
        {
            List<HospitalInfo> list = (List<HospitalInfo>)DAL_Hospital.GetHospitalinfoLevelDetail();
            List<string> list2 = new List<string>();
            for (int i = 0; i < list.Count; i++)
            {
                if (!string.IsNullOrEmpty(list[i].LevelDetail))
                {
                    list2.Add(list[i].LevelDetail);
                }
            }
            return list2;
        }

        /// <summary>
        /// 获取所有医疗机构等级
        /// </summary>
        /// <returns></returns>
        public List<string> GetHospitalinfoLevels()
        {
            List<HospitalInfo> list = (List<HospitalInfo>)DAL_Hospital.GetHospitalinfoLevels();
            List<string> list2 = new List<string>();
            for (int i = 0; i < list.Count; i++)
            {
                if (!string.IsNullOrEmpty(list[i].Levels))
                {
                    list2.Add(list[i].Levels);
                }
            }
            return list2;
        }
        /// <summary>
        /// 根据医疗机构等级获取用户ID
        /// </summary>
        /// <param name="LevelDetail"></param>
        /// <returns></returns>
        public string GetHospitalIDByLevelDetail(string LevelDetail)
        {
            List<HospitalInfo> list = (List<HospitalInfo>)DAL_Hospital.GetHospitalIDByLevelDetail(LevelDetail);
            StringBuilder str = new StringBuilder();
            for (int i = 0; i < list.Count; i++)
            {
                if (!string.IsNullOrEmpty(list[i].LevelDetail))
                {
                    str.Append(list[i].HospitalID+",");

                }
            }
            str.Remove(str.Length - 1, 1);
            return str.ToString() ;

        }
        #endregion


        public IList<Model.HospitalInfo> GetAllHopialInfo(Model.Query.HospitalInfo where, int currentpage, int pagesize, out int totalrecord)
        {
            IList<Model.HospitalInfo> list = DAL_Hospital.GetAllHopialInfo(where, currentpage, pagesize, out totalrecord);

            return list;
        }

        public DataTable GetAllHopialInfo2(Model.Query.HospitalInfo where, int currentpage, int pagesize, out int totalrecord)
        {
            return DAL_Hospital.GetAllHopialInfo2(where, currentpage, pagesize, out totalrecord);
        }

        public IList<Model.HospitalInfo> GetAllUnInitializeHopialInfo(string where, int currentpage, int pagesize, out int totalrecord)
        {
            IList<Model.HospitalInfo> list = DAL_Hospital.GetAllUnInitializeHopialInfo(where, currentpage, pagesize, out totalrecord);

            return list;
        }
    }
}
